//
//  JFBSotreInfoDS.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "JFBStoreInfoDS.h"
#import "JFBAPIClient.h"
#import "JFBGlobalSetting.h"
#import "JFBBaseStorage.h"
#import "JFBStoreInfo.h"

@implementation JFBStoreInfoDS
//更新营业状态
+ (NSURLSessionDataTask *)updateOperating:(void (^)(BOOL isSuccess, NSString *message, JFBStoreInfoDS *storeInfo, NSError *error))block currentStatus:(NSUInteger)currentStatus{

    NSUInteger nextStatus = -1;
    if( currentStatus == 0 ) {
        currentStatus = 1;
        nextStatus = 1;
    } else {
        currentStatus = 0;
        nextStatus = -1;
    }

    NSDictionary *parameter = @{@"opt_flag":[NSNumber numberWithInteger:nextStatus]};
    return [[JFBAPIClient sharedClient:true] GET:@"/shop/user/opt.json" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"error"];
        if( error == [NSNull null] ) {
            JFBStoreInfoDS * ds = [JFBStoreInfoDS updateStoreInfoStatus:currentStatus];
            block(true, @"更新成功", ds, nil);
        } else {
            NSObject * errorMsg = [JSON valueForKey:@"error"];
            block(false, [NSString stringWithFormat:@"%@", errorMsg], nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"更新失败", nil, error);
    }];
    return nil;
}

// 店主登录
+ (NSURLSessionDataTask *)login:(void (^)(BOOL isSuccess, NSString *message, NSDictionary *data, NSError *error))block username:(NSString*)username passwod:(NSString*)password {
    NSDictionary *parameters = @{@"username":username, @"password":password};
    
    return [[JFBAPIClient sharedClient:false] GET:@"/ouser-web/mobileLogin/loginForm.do" parameters:parameters success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@", JSON);
        NSDictionary *loginResponse = [JSON valueForKeyPath:@"ut"];
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual:@"0"] ) {
            //这里是将登录成功之后获取的ut存到本地来
            [[NSUserDefaults standardUserDefaults]setObject:[JSON valueForKeyPath:@"ut"] forKey:@"ut"];
//            NSLog(@"ut-------%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]);
            [UserInfo currentUser].ut = JSON[@"ut"];
            block(true, @"登录成功", loginResponse, nil);
            [[NSUserDefaults standardUserDefaults]setObject:@"111" forKey:@"first"];
        } else {
            block(false, @"密码错误", nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        NSLog(@"%@", error);
        block(false, @"登录失败，请稍候重试", nil, error);
    }];
}


// 在服务器注册PUSH的设备
+ (NSURLSessionDataTask *)registerDevice:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block  pushId:(NSString*)pushId {
    
    NSString *encodedValue = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(nil,
                                                                                (CFStringRef)pushId, nil,
                                                                                (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    
    NSDictionary * parameters = @{@"push_id":encodedValue, @"device_type":[NSNumber numberWithInt:2], @"shop_id":[NSNumber numberWithInteger:[JFBGlobalSetting getSetting].shopId]};
    
    return [[JFBAPIClient sharedClient:false] GET:@"/shop/push/user/bind.json" parameters:parameters success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * data = [JSON valueForKey:@"data"];
        NSLog(@"PUSH Reg:%@", JSON);
        if( data != nil) {
            block(true, @"别名注册成功", nil);
        } else {
            block(false, nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, nil, nil);
    }];
    return nil;
}

// 获取CoreData中的店铺信息
+ (NSURLSessionDataTask *)loadStoreInfo:(void (^)(JFBStoreInfoDS *storeInfo, NSError *error))block storeID:(NSUInteger)storeID{
    
    JFBStoreInfoDS * ds = [JFBStoreInfoDS loadFromDB];
    
    if( block ) {
        if( ds == nil ) {
            block(nil, nil);
        } else {
            block(ds, nil);
        }
        return nil;
    }
    
    return nil;
}

// 更新CoreData中的店铺信息
+ (NSURLSessionDataTask *)updateStoreInfo:(void (^)(BOOL isSuccess, NSString *message, JFBStoreInfoDS *storeInfo, NSError *error))block storeInfo:(JFBStoreInfoDS*)_storeInfo{
    
    JFBStoreInfoDS * ds = [JFBStoreInfoDS refreshStoreInfoDB:_storeInfo];
    
    if( block ) {
        block(DSDefaultResult, @"更新成功", ds, nil);
    }
    return nil;
}


+(JFBStoreInfoDS*)updateStoreInfoStatus:(NSUInteger)status{
    JFBBaseStorage *_store = [JFBBaseStorage getStore];
    // 初始化用户信息
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStoreInfo"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    JFBStoreInfo *storeInfo;
    
    if( array.count <= 0 ) {
        return nil;
    } else {
        storeInfo = [array objectAtIndex:0];
    }
    
    storeInfo.isStoreOpen = [NSNumber numberWithInteger:status];
    
    [_store.managedObjectContext save:&error];
    
    return [JFBStoreInfoDS loadFromDB];
}

// 更新店铺信息
+(JFBStoreInfoDS*)refreshStoreInfoDB:(JFBStoreInfoDS* )_storeInfo{
    JFBBaseStorage *_store = [JFBBaseStorage getStore];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStoreInfo"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    JFBStoreInfo *storeInfo;
    
    if( array.count <= 0 ) {
        return nil;
    } else {
        storeInfo = [array objectAtIndex:0];
    }
//    storeInfo.city_id = [NSNumber numberWithInteger:_storeInfo.city_id];
    storeInfo.name = _storeInfo.storeName;
    storeInfo.callcenterMobile = [_storeInfo.callcenterMobile componentsJoinedByString:@","];
    storeInfo.distribution = [NSNumber numberWithInteger:_storeInfo.distribution];
    storeInfo.isStoreOpen = [NSNumber numberWithInteger:_storeInfo.isStoreOpen];
    storeInfo.masterMobile = _storeInfo.masterMobile;
    storeInfo.min = _storeInfo.min;//[NSNumber numberWithInteger:_storeInfo.min];
    storeInfo.storeAddress = _storeInfo.storeAddress;
    
    storeInfo.timeRange = [_storeInfo.timeRange componentsJoinedByString:@","];
    storeInfo.workTime = _storeInfo.workTime;
    
    [_store.managedObjectContext save:&error];
    
    return [JFBStoreInfoDS loadFromDB];
}

// 从CoreData加载数据
+(JFBStoreInfoDS*)loadFromDB {
    JFBBaseStorage *_store = [JFBBaseStorage getStore];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStoreInfo"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    JFBStoreInfo *storeInfo;
    
    if( array.count <= 0 ) {
        return nil;
    } else {
        storeInfo = [array objectAtIndex:0];
    }
    
    JFBStoreInfoDS *ds = [[JFBStoreInfoDS alloc] init];
    ds.storeName = storeInfo.name;
    ds.ID = [storeInfo.shop_id intValue];
    ds.workTime = storeInfo.workTime;
    ds.callcenterMobile = [storeInfo.callcenterMobile componentsSeparatedByString:@","];
    ds.min = storeInfo.min;
    ds.distribution = [storeInfo.distribution intValue];
    ds.timeRange = [@[storeInfo.timeRange] mutableCopy];
    ds.masterName = storeInfo.masterName;
    ds.masterMobile = storeInfo.masterMobile;
    ds.storeAddress = storeInfo.storeAddress;
    ds.isStoreOpen = [storeInfo.isStoreOpen intValue];
    ds.city_id = storeInfo.city_id;
    ds.city_name = storeInfo.city_name;
    return ds;
}

// 保存或更新店铺信息
+(void)userInfoPersistence:(NSDictionary*)loginResponse{
//    NSString *homePath = NSHomeDirectory();
    JFBBaseStorage *_store = [JFBBaseStorage getStore];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBStoreInfo"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    JFBStoreInfo *storeInfo;
    
    if( array.count <= 0 ) {
        storeInfo = (JFBStoreInfo*)[NSEntityDescription insertNewObjectForEntityForName:@"JFBStoreInfo" inManagedObjectContext:[_store managedObjectContext]];
    } else {
        storeInfo = [array objectAtIndex:0];
    }
    storeInfo.city_name = [NSString stringWithFormat:@"%@",[loginResponse objectForKey:@"city_name"]];
    storeInfo.city_id = [NSString stringWithFormat:@"%@",[loginResponse objectForKey:@"city_id"]];
    storeInfo.shop_id = [loginResponse objectForKey:@"id"];
    storeInfo.name = [loginResponse objectForKey:@"name"];
    storeInfo.callcenterMobile = [loginResponse objectForKey:@"complain_phone"];
    storeInfo.distribution = [loginResponse objectForKey:@"delivery_scope"];
    storeInfo.isStoreOpen = [[loginResponse objectForKey:@"status"]intValue] == 1 ? [NSNumber numberWithInt:1] : [NSNumber numberWithInt:0];
    storeInfo.masterMobile = [loginResponse objectForKey:@"contact_phone"];
    storeInfo.masterName = [loginResponse objectForKey:@"contact_name"];
    storeInfo.min = [NSString formatDecimal:[loginResponse objectForKey:@"send_fee"]];//[loginResponse objectForKey:@"send_fee"];
    storeInfo.storeAddress = [NSString stringWithFormat:@"%@%@", [loginResponse objectForKey:@"address_name"], [loginResponse objectForKey:@"address_detail"]];
    NSString *startTime = [loginResponse objectForKey:@"open_start"];
    if( startTime != nil ) {
        startTime = [startTime substringWithRange:NSMakeRange(11, 5)];
    }
    NSString *endTime = [loginResponse objectForKey:@"open_end"];
    if( endTime != nil ) {
        endTime = [endTime substringWithRange:NSMakeRange(11, 5)];
    }
    storeInfo.timeRange = [NSString stringWithFormat:@"%@ - %@", startTime, endTime];
    storeInfo.workTime = storeInfo.timeRange;
    
    [_store.managedObjectContext save:&error];
}
@end
